
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;

public class Main implements Runnable {
	
	private static final int MEM_MAP_SIZE = 5460;
	private static final String MEM_MAP_NAME = "MumbleLink";
	private final HANDLE sharedFile;
	private Pointer sharedMemory;
	private char[] characterName;
	private long oldId;
	private long worldID;
	private Frame frame;
	private String[] name;

	public static void main(String[] args) {
		new Main();		
	}
	
	public Main(){
		characterName = new char[0];
		this.sharedFile = Kernel32.INSTANCE.CreateFileMapping(WinBase.INVALID_HANDLE_VALUE, null, WinNT.PAGE_EXECUTE_READWRITE, 0, MEM_MAP_SIZE, MEM_MAP_NAME);
		this.sharedMemory = Kernel32.INSTANCE.MapViewOfFile(this.sharedFile, WinNT.SECTION_MAP_READ, 0, 0, MEM_MAP_SIZE);		
		frame = new Frame(this); 
		this.run();
	}

	@Override
	public void run() {
		while (true){
			try {
				frame.repaint();
				refresh();
				frame.update();
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public void refresh(){		
		if (this.sharedMemory != null) {
			characterName = this.sharedMemory.getCharArray(592, 256);
			StringBuilder nameString = new StringBuilder();
			
			for (char c : characterName ){
				if(c !='\0'){
					nameString.append(c);
				} else {
					nameString.append(" ");
				}
			}
			String[] info = nameString.toString().split(",");
			name = info[0].split("\"");
			
			for (String s : info){
				String [] alt = s.split(": ");				
			
				if (alt[0].equals("\"world_id\"")){
					worldID=Long.parseLong(alt[1]);
				}
			}
			if (worldID!=oldId){
				oldId= worldID;
			}			
		}		
	}
	
	public long getWorldID() {
		return worldID;
	}
	
	public String getName(){
		if (name.length > 2){
			return name[3];
		} else {
			return null;
		}
		
	}
}
